<template>
  <div>
    <!-- 导航 -->
    <van-tabs v-model="active" @click="tabactive">
      <van-tab title="销量" click="active" />
      <van-tab title="新品" click="active" />
      <van-tab title="价格" click="active" />
    </van-tabs>
    <!-- 商品列表 -->
    <van-list v-if="bool">
      <van-card
        :price="item.price"
        :desc="item.message"
        :title="item.name"
        :thumb="item.src[0]"
        :origin-price="item.size"
        @click="godetails(item.good_id)"
        :key="item.good_id"
        v-for="item in list"
      >
        <template #footer>
          <van-icon name="add-o" size="0.2222rem" color="#11b57c" @click.stop="add(item.good_id)" />
        </template>
      </van-card>
      <van-loading v-show="loading" size="24px">加载中...</van-loading>
      <div class="loadbox" v-show="many" @click="updata">{{loadmessage?"点击加载更多":"我是有底线的"}}</div>
    </van-list>
    <div class="nogood" v-if="!bool">
      <div>
        
      </div>
      <p>找不到该商品</p>
    </div>
    <van-icon v-if="btnFlag" class="go-top" name="upgrade" @click="backTop" />
    <!-- 购物车键 -->
    <van-icon
      name="cart-o"
      class="iconcart"
      :badge="cart.length!=0?cart.length:''"
      size="0.2564rem"
      @click="gocart"
    />
    <!-- 返回列表 -->
    <van-icon name="arrow-left" class="iconback" size="0.2564rem" @click="golist" />

    <!-- 添加购物车遮罩 -->
    <van-overlay :show="show" @click="show = false">
      <div class="wrapper" @click.stop="show = false">
        <div class="block">{{message}}</div>
      </div>
    </van-overlay>
    <!-- <img   src="../../assets/img/icon_top.png" > -->
  </div>
</template>

<script>
import goodApi from "@/api/goodApi";
import { getUser, getToken } from "@/utils/auth";
export default {
  data() {
    return {
      message: "加入购物车成功",
      page: 0, //当前页
      pagenum: 1,
      pagea: 0,
      //列表
      list: [],
      //用户购物车数量
      btnFlag: false,
      loading: false,
      many:true,
      finished: false,
      show: false,
      loadmessage: true,
      //标签选中下标
      active: 0,
      loginstatus: {},
      cart: [],
      bool:true
      }
  },

  components: {},
  mounted() {
    window.addEventListener("scroll", this.scrollToTop);
  },
  destroyed() {
    window.removeEventListener("scroll", this.scrollToTop);
  },

  methods: {
    //进入购物车
    gocart() {
      if (this.loginstatus.flag) {
        // 购物车地址
        this.$router.push("/cart");
      } else {
        this.$toast("请登录");
        setTimeout(() => {
          this.$router.push("/LRcom/login");
        }, 1000);
      }
    },
    // 返回列表
    golist() {
      this.$router.push("/list");
    },
    //点击加载下一页的内容
    updata() {
      this.loading = true;
      this.many = false
      setTimeout(() => {
        if (this.active == 0) {
          if (this.page < this.pagenum) {
            this.adddata();
          } else {
            this.loadmessage = false;
          }
        } else {
          if (this.pagea > 1) {
            this.adddata2();
          } else {
            this.loadmessage = false;
          }
        }
        this.loading = false;
        this.many = true
      }, 1500);
    },
    // 点击图片回到顶部方法，加计时器是为了过渡顺滑
    backTop() {
      const that = this;
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 5);
        document.documentElement.scrollTop = document.body.scrollTop =
          that.scrollTop + ispeed;
        if (that.scrollTop === 0) {
          clearInterval(timer);
        }
      }, 16);
    },

    // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    scrollToTop() {
      const that = this;
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      that.scrollTop = scrollTop;
      if (that.scrollTop > 60) {
        that.btnFlag = true;
      } else {
        that.btnFlag = false;
      }
    },
    //点击标签重新渲染
    tabactive() {
      if (this.active == 0) {
        this.page = 0;
        this.pagenum = 1;
        this.list = [];
        this.adddata();
        console.log(22);
      } else if (this.active == 1) {
        console.log(this.list);
        this.pagea = this.pagenum;
        this.list = [];
        this.adddata2();
      }
    },
    
    
    //加载数据
    async adddata2() {
      if (this.pagea > 1) {
        try {
          let p = await goodApi.goodlist(this.pagea);
          if (p.data.flag) {
            p.data.data.forEach(item => {
              item.src = item.src.replace("[", "");
              item.src = item.src.replace("]", "");
              item.src = item.src.split(",");
              this.list.push(item);
            });
            // this.pagenum = p.data.pages;
            this.pagea--;
          } else {
            this.$message({
              message: p.data.message,
              type: "warnning"
            });
          }
        } catch (error) {
          console.log(error);
        }
      } else {
        this.loading = false;
        this.many = true
      }
    },
     async adddata() {
      if (this.page < this.pagenum) {
        try {
          this.page++;
          let p = await goodApi.goodlist(this.page);
          if (p.data.flag) {
            p.data.data.forEach(item => {
              //格式src字符串，转成数组
              item.src = item.src.replace("[", "");
              item.src = item.src.replace("]", "");
              item.src = item.src.split(",");
              this.list.push(item);
            });
            this.pagenum = p.data.pages;
            this.pagea = this.pagenum;
          } else {
            this.page--;
            this.$toast.fail("加载失败");
            this.$message({
              message: p.data.message,
              type: "warnning"
            });
          }
        } catch (error) {
          console.log(error);
          this.fail();
          // this.finished = true
          // this.finished_text = "网络异常，请稍后再试"
        }
      } else {
        this.loadmessage = false;
        // this.finished = true
      }
    },
    //判断路径是否有值
    getlist(){
      if(this.$route.fullPath.split("?")[1]){

        this.getsearch(this.$route.fullPath.split("?")[1])
      }else(
        this.adddata()
      )
    },

    //模糊查询请求
    async getsearch(val){
      try {
        let p= await goodApi.search(decodeURI(val))
        if(p.data.flag){
          p.data.data.forEach(item => {
              //格式src字符串，转成数组
              item.src = item.src.replace("[", "");
              item.src = item.src.replace("]", "");
              item.src = item.src.split(",");
              this.list.push(item);
            });
        }else{
          this.bool = false
          console.log(p.data.data);
        }

      } catch (error) {
        console.log(error);
      }
      this.many = false
    },
    //验证token
    async checktoken() {
      let token = getToken();
      let user = getUser();
      user = JSON.parse(user);
      if (token && user) {
        try {
          //到时候修改接口方法
          let p = await goodApi.checktoken(token);
          if (p.data.flag) {
            this.loginstatus = { flag: true, code: 200 };
          } else {
            // 校验失败返回登录页

            // this.show = true;
            // this.message = "请登录";
            // this.$router.push("/login");
            this.loginstatus = { flag: false, code: 301 };
            //301未登录
            //302服务器异常
          }
        } catch (error) {
          //异常也跳回登录页
          // this.show = true;
          // this.message = "服务器异常";
          this.loginstatus = { flag: false, code: 302 };
        }
      } else {
        //没有token或user_id 返回登录页
        // this.show = true;
        // this.message = "请登录";
        // this.$router.push("/login");
        this.loginstatus = { flag: false, code: 301 };
      }
    },
    //添加购物车
    async addcart(good_id) {
      let user = getUser();
      user = JSON.parse(user);

      try {
        let p = await goodApi.addcart(user.userphone, 1, good_id);
        if (p.data.flag) {
          //添加成功
          let bool = false;
          this.cart.forEach(item => {
            if (item == good_id) {
              bool = true;
            }
          });
          if (!bool) {
            this.cart.push(good_id);
          }
          this.$toast.success("添加购物车成功");
        } else {
          //添加失败
          this.$fail("添加购物车失败");
        }
      } catch (error) {
        //添加失败弹窗
        console.log(error);
        this.$toast.fail("网络异常");
      }
    },
    //添加购物车按钮
    add(good_id) {
      if (this.loginstatus.flag) {
        this.addcart(good_id);
      } else {
        if (this.loginstatus.code == 301) {
          this.$toast.fail({
            message: "请登录"
          });
          setTimeout(() => {
            this.$router.push("/LRcom/login");
          }, 1000);
        } else {
          this.$toast.fail("网络异常");
        }
      }
      // this.show = true;
      // this.message = num + "添加成功";
      // if(this.checktoken()){
      //   this.addcart(num)
      // }
    },
    //查询当前用户的购物车
    async checkcart() {
      let user = getUser();
      user = JSON.parse(user);
      try {
        let p = await goodApi.cheackcart(user.userphone);
        console.log(p);
        if (p.data.flag) {
          p.data.data.forEach(item => {
            this.cart.push(item.good_id);
          });
        } else {
          console.log(p.data);
        }
      } catch (error) {
        console.log(error);
      }
    },
    //前往详情
    godetails(good_id) {
      this.$router.push("/details?" + good_id);
    }
  },
  watch: {},
  //使用created() 在也面未加载是发送请求渲染数据
  created() {
    this.checktoken();
    this.checkcart();
    this.getlist();

    // this.formatsrc()
  }
};
</script>

<style scoped>
/* 查询不到页面 */
.nogood{
  height: 5.2991rem;

}
.nogood p {
   position: absolute;
   left: 33%;
   top: 60%;
   color: #ddd;
   font-size: 0.1709rem;
}
.nogood div{
  position: absolute;
    left: 50%;
    top: 50%;
    margin-left: -64px;
    margin-top: -64px;
  background: url("../../assets/img/nogood.png") no-repeat  center;
  background-size:35%;
    background-attachment:fixed;
  width: 128px;
  height: 128px;
  
}
/* iconcart */
.iconcart {
  position: fixed;
  bottom: 0.9829rem;
  right: 0.1197rem;
  background: #000;
  opacity: 0.7;
  border-radius: 5px;
}
.iconback {
  position: fixed;
  bottom: 1.5rem;
  right: 0.1197rem;
  background: #000;
  opacity: 0.7;
  border-radius: 5px;
}
.van-card__content {
  text-align: left;
}
.van-card:not(:first-child) {
  margin-top: 0;
}
.van-card__footer {
  position: absolute;
  bottom: 0;
  right: 0.1709rem;
}
</style>
<style >
.van-card {
  background-color: #fff !important;
  height: 1.0256rem;
  border-bottom: 0.0085rem solid #ddd !important;
}
.van-tabs__line {
  width: 33.33vw !important;
  /* border-bottom: 0.0171rem solid #11B57C;
    box-sizing: border-box;
    color: #11B57C; */
}
.van-tab--active {
  color: #11b57c !important;
}
.van-cardvan-tab {
  font-size: 0.1026rem !important ;
}
.go-top {
  font-size: 0.2735rem !important;
  position: fixed !important;
  right: 0.1709rem !important;
  bottom: 0.5983rem !important;
  width: 0.2051rem !important;
  height: 0.2051rem !important;
  background: #fff !important;
  opacity: 0.6 !important;
}
/* 添加购物车遮罩 */
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  font-size: 0.1368rem;
  width: 120px;
  height: 120px;
  background-color: #fff;
}

.loadbox {
  background: #fff;
  color: gray;
  height: 0.2564rem;
  width: 100%;
  text-align: center;
  line-height: 0.3419rem;
  font-size: 0.1709rem;
}
</style>